<template>
    <div class="pageContainer">
        <el-container class="bg-white rounded-lg">
            <el-header class="flex items-center justify-between" style="border-bottom: 1px solid #eeeeee;">
                <div>
                    <el-button type="primary" @click="onAdd">新增用户</el-button>
                    <el-popconfirm title="确定批量删除这些用户吗？" @confirm="onMultiDelete">
                        <template #reference>
                            <el-button type="primary">批量删除</el-button>
                        </template>
                    </el-popconfirm>
                </div>
                <el-button type="primary" text @click="onSearch">
                    <el-icon :size="20">
                        <Refresh />
                    </el-icon>
                </el-button>
            </el-header>
            <el-container>
                <div class="w-full">
                    <el-table :data="tableData" style="width: 100%" :row-class-name="tableRowClassName"
                        @selection-change="onSelectionChange">
                        <el-table-column type="selection" width="40" />
                        <el-table-column label="序号" width="90" align="center" fixed="left" prop="rank">
                            <template #default="{ $index, row }">
                                {{ (currentPage - 1) * limit + $index + 1 }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="username" label="用户名" min-width="150" />
                        <el-table-column prop="nickname" label="昵称" min-width="150" />
                        <el-table-column prop="phone" label="手机号" min-width="150" />
                        <el-table-column prop="email" label="邮箱" min-width="150" />
                        <el-table-column prop="user_level.name" label="会员等级" min-width="150" />
                        <el-table-column label="注册时间" width="200">
                            <template #default="{ row }">
                                {{ dayjs(row.create_time).format('YYYY-MM-DD HH:mm:ss') }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="status" label="状态" min-width="150">
                            <template #default="{ $index, row }">
                                <el-switch v-model="row.status" :active-value="1" :inactive-value="0" size="small"
                                    @change="onStatusChange(row)" />
                            </template>
                        </el-table-column>
                        <el-table-column fixed="right" label="操作" min-width="200" align="center">
                            <template #default="scope">
                                <el-button link type="primary" @click="onEdit(scope.row)">修改</el-button>
                                <el-popconfirm title="确定删除该用户吗？" @confirm="onDelete(scope.row)">
                                    <template #reference>
                                        <el-button type="primary" link>删除</el-button>
                                    </template>
                                </el-popconfirm>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div style="height: 50px;" class="flex items-center justify-center">
                        <el-pagination layout="prev, pager, next" background :current-page="currentPage"
                            :total="totalCount" :page-size="10" @current-change="onPageChange" />
                    </div>
                </div>
            </el-container>
        </el-container>
        <FormDrawer ref="drawerRef" :title="drawerTitle" @submit="onSubmit">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username" placeholder="请输入用户名" clearable />
                </el-form-item>
                <el-form-item v-if="form.id === 0" label="密码" prop="password">
                    <el-input v-model="form.password" type="password" placeholder="请输入密码" clearable />
                </el-form-item>
                <el-form-item v-if="form.id === 0" label="确认密码" prop="confirmPassword">
                    <el-input v-model="form.confirmPassword" type="password" placeholder="请再次输入密码" clearable />
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="form.nickname" placeholder="请输入昵称" clearable />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="form.phone" placeholder="请输入手机号" clearable />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="请输入邮箱" clearable />
                </el-form-item>
                <el-form-item label="会员等级" prop="user_level_id">
                    <el-select v-model="form.user_level_id" placeholder="请选择会员等级">
                        <el-option
                            label="普通会员"
                            :value="3"
                        />
                        <el-option
                            label="黄金会员" 
                            :value="6"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
                </el-form-item>
            </el-form>
        </FormDrawer>
    </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import dayjs from 'dayjs'
import { getUsersList, addUser, updateUserById, deleteUserById, updateUserStatusById } from '../../api/user'
import FormDrawer from '../../components/FormDrawer.vue'
import { useTableSearch, useForm } from '../../composables/common'

// 查询相关
const searchform = reactive({
    keyword: "",
})

const clearSearchform = () => {
    searchform.keyword = ''
}

const {
    tableRowClassName,
    onSearch,
    getData,
    onClearSearch,
    onPageChange,
    currentPage,
    tableData,
    totalCount,
    limit,
    userLevels
} = useTableSearch({
    searchform,
    getTableList: (params) => getUsersList(currentPage.value, params),
    clearSearchform
})

const form = reactive({
    id: 0,
    username: '',
    password: '',
    confirmPassword: '',
    nickname: '',
    phone: '',
    email: '',
    user_level_id: '',
    status: 1,
    create_time: '',
    update_time: ''
})

const validatePasswordComplexity = (rule, value, callback) => {
    const hasUpperCase = /[A-Z]/.test(value)
    const hasLowerCase = /[a-z]/.test(value)
    const hasNumber = /\d/.test(value)
    const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value)
    
    if (!hasUpperCase || !hasLowerCase || !hasNumber || !hasSpecialChar) {
        callback(new Error('密码必须包含大写字母、小写字母、数字和特殊字符'))
    } else {
        callback()
    }
}

const validatePassword = (rule, value, callback) => {
    if (value !== form.password) {
        callback(new Error('两次输入的密码不一致'))
    } else {
        callback()
    }
}

const rules = {
    username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
    password: [
        { 
            required: form.id === 0, 
            message: '密码不能为空', 
            trigger: 'blur' 
        },
        {
            min: 8,
            message: '密码长度至少为8个字符',
            trigger: 'blur'
        },
        {
            validator: validatePasswordComplexity,
            trigger: 'blur'
        }
    ],
    confirmPassword: [
        { 
            required: form.id === 0,
            message: '请再次输入密码',
            trigger: 'blur'
        },
        { 
            validator: validatePassword,
            trigger: 'blur'
        }
    ],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    phone: [{ required: false }],
    email: [{ required: false }],
    nickname: [{ required: false }],
    user_level_id: [{ required: false }]
}

const {
    formRef,
    drawerRef,
    drawerTitle,
    onAdd,
    onEdit,
    onDelete,
    onSubmit,
    onStatusChange,
    onSelectionChange,
    onMultiDelete
} = useForm({
    title: '用户',
    form,
    tableData,
    getData,
    add: addUser,
    update: updateUserById,
    delete: deleteUserById,
    updateStatus: updateUserStatusById,
})
</script>
